<?php


include("pznahar.php");
DBConnect::$useMemCache = false;

/*
$sql = "INSERT INTO `".PREFIX_STATIC."level` (`level`, `practic`) VALUES ";
        $i = 1;
        $p = -44;
        while($i <= 100){
            if($i > 19){
                $p = $p + 79;    
            }
            else{
                $p = $p + 44;
            }
            $sql .= "( '".$i."', '". ($p) ."')";
            $sql .= ($i != 100) ? " , " : "";    
            $i++;
        }
_echo($sql);
*/


session_start();
class pznaharAdmin extends Connect{
        
    
    public function beforeFilter( $calledFunc ){                            
        return true;
        if(isset($_SESSION['authAdmin']) ){
            return true;
        } 
        return in_array( $calledFunc, array('auth') );         
    }

    
    function testtt($data){
        return $data;
    }
    
    
    function auth($data){
        /**
         * admin
         * 412nak4XDQ
        */
        $data = DBConnect::checkData($data);
        $sql = "SELECT * FROM `".PREFIX_TABLE."admins` WHERE `name` = '".$data[0]."' AND `pass` = '".md5($data[1])."'";
        _echo($sql);
        if(!$result = DBConnect::query($sql)){
            $this->_error(mysql_error());
            return $this->answer(false);
        }
        if(DBConnect::mysqlCount($result) == 0){
            return $this->answer(false);
        }
        $_SESSION['authAdmin'] = 1;
        return $this->answer(true);
    }
    
    function updateSession(){
        
        
        
    } 
    
    
    /**
     * Tree
    */
    function getTree(){
        $t = @array_values( Tree::getTree() );
        return $this->answer( $t[0] );
    }
    /**
     * Save Tree
    */
    function saveTree($data){
        $data = DBConnect::checkData($data[0]);
        $p = new Tree();
        return  $this->answer( $p->saveTree($data) );        
    }
    
    
    /**
     * PEt
    */
    function getPet(){
        $p = array_values( Pet::getPets() );
        $p[0]['skins'] = array_values($p[0]['skins']);
        return $this->answer( $p[0] );
    }
    /**
     * Save Pet
    */
    function savePet($data){
        $data = DBConnect::checkData($data[0]);
        $p = new Pet();
        return  $this->answer( $p->savePet($data) );
        
    }
    
    /**
    * tutorials
    */
    function getTutorials(){
        $t = new Tutorial();
        return $this->answer( array('t' => $t->getTutorials(), 'type' => Tutorial::$type ) );
    }
    /**
     * [id, type, text]
    */
    function saveTutorial($data){
        $data = DBConnect::checkData($data);
        $t = new Tutorial(); 
        if( intval($data[0]) == 0 ){
            return $this->answer( $t->newTutorial($data[1], $data[2]) );    
        }       
        return $this->answer( $t->saveTutorials($data[0], $data[1], $data[2]) );
    }
    
    /**
     * [type, text]
    */
    function newTutorial($data){
        $data = DBConnect::checkData($data);
        $t = new Tutorial();        
        return $this->answer( $t->newTutorial($data[0], $data[1] ) );
    }
    
    /**
     * [id]
    */
    function delTutorial($data){
        $id = DBConnect::checkData($data[0]);
        $t = new Tutorial();        
        return $this->answer( $t->delTutorial( $id ) );
    }
    
    /**
     * Presents
    */
    function getPresents(){
        $p = new Present();
        return $this->answer($p->getAll());
    }
    
    /**
     * del Present [id]
    */
    function delPresent($data){
        $id = DBConnect::checkData($data[0]);
        $p = new Present();
        return $this->answer($p->deletePresent($id));
    }
    /**
     * new Present [type, id ]
    */
    function newPresent($data){
        $data = DBConnect::checkData($data);
        $p = new Present();
        return $this->answer($p->setPresent( $data[0], $data[1] ));
    }
    
    /**
     * game config
    */
    function getGameConfig(){
        $a = array();
        $a['recreate'] = RECREATE;
        $a['curs'] = CURS;
        $a['media'] = MEDIA_URL;
        return $this->answer($a);
    }
    /**
     * save game config
    */
    function saveGameConfig($data){
        $data = DBConnect::checkData($data[0]);
        #return $data;
        
        $file = fopen(CORE_PATH."gameconfig.inc.php", "w");
        $t = "<?php \n";
        $t .= "define(\"RECREATE\", ".$data['recreate']."); #время пересоздания хабара (s);\n";
        $t .= "define(\"CURS\", ".$data['curs']."); #Курс золота к серебру;\n";
        $t .= "define(\"MEDIA_URL\", '".$data['media']."'); #медия (s);\n";
        $t .= "?>" ;
        
        fwrite($file,  $t );
        fclose($file);  
        return $this->answer(true);                      
    }
    
    
    /**
     * 
    */
    function changeGoodCount($data){
       $data = DBConnect::checkData($data);
       $s = new Storage();
       if($data[2] > 0){             
            return $this->answer($s->add($data[0], $data[1], $data[2]));
       }else{ 
            return $this->answer($s->del($data[0], $data[1], $data[2]));
       } 
    }
    
    
    /**
     * [5357114]
     * [14921442]
     * [5052803]
     * [18557049]
    */    
    function getMyGoods($data){
        $user = DBConnect::checkData($data[0]);
        $s = new Storage();
        $a = array();
        
        $a['clothing'] =  $s->getMy($user, 'clothing');  
        $a['artifact'] = $s->getMy($user, 'artifact');
        $a['boiler'] = $s->getMy($user, 'boiler');
        $a['mortar'] = $s->getMy($user, 'mortar');
        $a['podkova'] = $s->getMy($user, 'podkova');
        $a['food'] = $s->getMy($user, 'food');
        $a['seed'] = $s->getMy($user, 'seed');
        $a['user'] = $user;
        
        return $this->answer($a);
    } 
    
    function saveUserInfo($data){
        $user = DBConnect::checkData($data);
        $u = new User();
        $_SESSION['user'] = array();
        $_SESSION['user']['kontaktid'] = $data[0];
        $_SESSION['user']['level'] = $data[1]['level'];
        $_SESSION['user']['practic'] = $data[1]['practic'];
        $_SESSION['user']['levelpet'] = $data[1]['levelpet'];
        $_SESSION['user']['practicpet'] = $data[1]['practicpet'];
        $_SESSION['user']['money1'] = $data[1]['money1'];
        $_SESSION['user']['money2'] = $data[1]['money2'];
        $a = $u->save();
        if($a !== false){
            $id = $_SESSION['user']['kontaktid'];
            $_SESSION['user'] = array();
            return $this->answer($id);
        }
        return $this->answer($a);
    }
    
    function getUserInfo($data){
        $user = DBConnect::checkData($data[0]);
        $u = new User();
        $a = $u->getUser($user, false, true);
        $_SESSION['user'] = array();
        return $this->answer($a);
    }
    
    function saveGlava($data){
        $data = DBConnect::checkData($data[0]);
        $b = new Book();        
        return $this->answer($b->saveGlava($data));
    }
    
    function addGlava($data){
        $data = DBConnect::checkData($data[0]);
        $b = new Book();        
        return $this->answer($b->addGlava($data));
    }
    
    function saveGreen($data){
        $data = DBConnect::checkData($data[0]);
        $b = new Book();        
        return $this->answer($b->save($data));
    }
    
    function addGreen($data){
        $data = DBConnect::checkData($data[0]);
        $b = new Book();        
        return $this->answer($b->add($data));
    }
    
    function delGreen($data){
        $id = DBConnect::checkData($data[0]);
        $b = new Book();        
        return $this->answer($b->delete($id));
    }
    
    function delGlava($data){
        $id = DBConnect::checkData($data[0]);
        $b = new Book();        
        return $this->answer($b->deleteGlava($id));
    }
    
    function saveChance($data){
        #return $data[0];
        $data = DBConnect::checkData($data[0]);        
        $habar = new Habars;
        return $this->answer($habar->saveChance($data));
    }
    
    function saveHabar($data){
        #return $data[0];
        $data = DBConnect::checkData($data[0]);        
        $habar = new Habars;
        return $this->answer($habar->save($data));
    }
    function newHabar($data){
        $data = DBConnect::checkData($data[0]);        
        $habar = new Habars;
        return $this->answer($habar->add($data));
    }
    function deleteHabar($data){
        $data = DBConnect::checkData($data[0]);        
        $habar = new Habars;
        return $this->answer($habar->delete($data));
    }
    
    function delGood($data){
        $data = DBConnect::checkData($data);        
        $artifact = new Goods;
        return $this->answer($artifact->delete($data[0], $data[1]));
    }
    function addGood($data){
        $data = DBConnect::checkData($data);        
        $artifact = new Goods;
        return $this->answer($artifact->add($data[0], $data[1]));
    }
    function saveGood($data){
        $data = DBConnect::checkData($data);        
        $artifact = new Goods;
        return $this->answer($artifact->save($data[0], $data[1]));
    }
    
    function saveArtifact($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        $artifact = new Goods;
        return $this->answer($artifact->save($data, "artifact"));
    }
    function newArtifact($data){
        #return $data;
        $data = DBConnect::checkData($data[0]);        
        $artifact = new Goods;        
        return $this->answer($artifact->add($data, "artifact"));
    }
    
    function saveClothing($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        $clothing = new Goods;
        return $this->answer($clothing->save($data, "clothing"));
    }
    function newClothing($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        $clothing = new Goods;
        return $this->answer($clothing->add($data, "clothing"));
    }
    
    function saveBoiler($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        $boiler = new Goods;
        return $this->answer($boiler->save($data, "boiler"));
    }
    function newBoiler($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        $boiler = new Goods;
        return $this->answer($boiler->add($data, "boiler"));
    }
    
    function saveMortar($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        $mortar = new Goods;
        return $this->answer($mortar->save($data, "mortar"));
    }
    function newMortar($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        $mortar = new Goods;
        return $this->answer($mortar->add($data, "mortar"));
    }
    
    function savePodkova($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        $mortar = new Goods;
        return $this->answer($mortar->save($data, "podkova"));
    }
    function newPodkova($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        $mortar = new Goods;
        return $this->answer($mortar->add($data, "podkova"));
    }
    
    function saveFood($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        #$food = new Food;
        $food = new Goods;
        return $this->answer($food->save($data, "food" ));
    }
    function newFood($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        #$food = new Food;
        $food = new Goods;
        return $this->answer($food->add($data, "food" ));
    }
    
    function saveExchange($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        $ex = new Exchange;
        return $this->answer($ex->save($data));
    }
    
    function newExchange($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        $ex = new Exchange;
        return $this->answer($ex->add($data));
    }
    
    function saveSeed($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        $se = new Seed();
        return $this->answer($se->save($data));
    }
    
    function saveCvest($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        $ex = new Cvest();
        return $this->answer($ex->save($data));
    }
    
    function newCvest($data){
        //return $data;
        $data = DBConnect::checkData($data[0]);        
        $ex = new Cvest();
        return $this->answer($ex->add($data));
    }
    
    function delCvest($data){
        //return $data;
        $parent = DBConnect::checkData($data[0]);        
        $ex = new Cvest();
        return $this->answer($ex->delete($parent));
    }
    
    /**
     * 
     * Магические свойства
    */
    function getMagic(){
        $m = new Magic();
        $m->getType();
        Magic::getAll();
        #$this->_error("error");
        $arr = array(
                "glade" => array("element" => 0, "idelement" => 0, "value" => 0, "timelive" => 1, "force" => 1 ),
                "drier" => array("element" => 1, "idelement" => 1, "value" => 0, "timelive" => 1, "force" => 1 ),
                "collection" => array("element" => 1, "idelement" => 1, "value" => 0, "timelive" => 1, "force" => 0 ),
                "mortar" => array("element" => 0, "idelement" => 0, "value" => 1, "timelive" => 0, "force" => 0 ),
                "boiler" => array("element" => 0, "idelement" => 0, "value" => 0, "timelive" => 0, "force" => 1 ),
                "invisible" => array("element" => 0, "idelement" => 0, "value" => 0, "timelive" => 1, "force" => 0 ),
                "education" => array("element" => 0, "idelement" => 0, "value" => 1, "timelive" => 0, "force" => 0 ),
                "message" => array("element" => 0, "idelement" => 0, "value" => 1, "timelive" => 1, "force" => 0 ),
                "moreforce" => array("element" => 0, "idelement" => 0, "value" => 0, "timelive" => 0, "force" => 1 ),
                "replace" => array("element" => 0, "idelement" => 0, "value" => 1, "timelive" => 1, "force" => 0 ),
                "bonuspotion" => array("element" => 0, "idelement" => 0, "value" => 0, "timelive" => 0, "force" => 1 ),
                "practic" => array("element" => 0, "idelement" => 0, "value" => 0, "timelive" => 0, "force" => 1 ),
            );
        
        foreach(Magic::$all as $key => $val){
            #Magic::$all[$key]["prop"] = $arr[$val["name"]];
            Magic::$all[$key]["prop"] = Magic::$type[$val["name"]];
        }
                  
        return $this->answer(Magic::$all);   
    } 
    
    function getOracle(){
        $m = new Magic();
        return $this->answer($m->getOracle());    
    }
    
    function saveOracle($data){
        $data = DBConnect::checkData($data[0]); 
        $m = new Magic();
        return $this->answer($m->saveOracle($data));    
    }
    
    function addOracle($data){
        $data = DBConnect::checkData($data[0]);        
        $m = new Magic();
        return $this->answer($m->addOracle($data));    
    }
    
    function delOracle($data){
        $id = DBConnect::checkData($data[0]);        
        $m = new Magic();
        return $this->answer($m->delOracle($id));    
    }
    
    
    
    
    /**
     * 
     * Поваренная книга [kontaktid, глава книги]
    */
    function getBook(){
        $user = new User();          
        return $this->complete($user->getBook(0));   
    } 
    
    function getArtifact(){
        Goods::getAll();
        #return  Goods::$all;        
        return $this->answer(Goods::$all["artifact"]);     
    }
    
    function getClothing(){
        Goods::getAll();         
        return $this->answer(Goods::$all["clothing"]);     
    }
    
    function getMortar(){
        Goods::getAll();         
        return $this->answer(Goods::$all["mortar"]);     
    }
    
    function getBoiler(){
        Goods::getAll();         
        return $this->answer(Goods::$all["boiler"]);    
    }
    
    function getPodkova(){
        Goods::getAll();         
        return $this->answer(Goods::$all["podkova"]);
    }
    
    function getFood(){
        Goods::getAll();         
        return $this->answer(Goods::$all["food"]);
        /*Food::getAll();         
        return $this->answer(Food::$all);*/
    }
    
    function getSeed(){
        Seed::getAll();         
        return $this->answer(Seed::$all);
    } 
    
    function getGoods(){
        Shop::getAll();       
        $a = array();
        $a['clothing'] = Shop::$clothing;  
        $a['artifact'] = Shop::$artifact;
        $a['boiler'] = Shop::$boiler;
        $a['mortar'] = Shop::$mortar;
        $a['podkova'] = Shop::$podkova;
        $a['food'] = Shop::$food;
        $a['seed'] = Shop::$seed;
        $a['skin'] = Shop::$skin;
        return $this->answer($a);
    }                 
    
    /**
     * []
     * habars
     * 
    */
    function getHabars(){
        Habars::getHabars();
        $arr = array("habar" => array("practic" => 1, "timedrying" => 0, 
                                        "descript" => 1, "buy1"=>0,
                                        "buy2" => 0, "sell1" => 0, "sell2" => 0, 
                                        "image"=>1, "timelive" => 1,
                                        "discount" => 0),
                     "element" => array("practic" => 0, "timedrying" => 1, 
                                        "descript" => 1, "buy1"=>1,
                                        "buy2" => 1, "sell1" => 1, "sell2" => 1, 
                                        "image"=>1, "timelive" => 0, "discount" => 1)  ); 
        return $this->answer(array("habars" => Habars::$habars, 
                                    "types" => Habars::getTypes(), 
                                    "enabled" => $arr) );     
    } 
    
    /**
     * levels
    */
    function getLevels(){
        $l = new Level();
        return  $this->answer( $l->getAll() );
    }
    function saveLevel($data){
        $data = DBConnect::checkData($data[0]);
        $l = new Level();
        return  $this->answer( $l->save($data) );
    }
    
    function getExchange(){
        Exchange::getAll();
        return $this->answer(Exchange::$all );
    }     
    
    /**
     * Квесты
    */
    function getCvest(){
        $c = new Cvest();
        $c->getAll(true);
        return $this->answer(Cvest::$all);   
    }
    /**
     * Инфо
    */
    function getCvestParams(){
        $c = new Cvest();        
        return $this->answer(array("action" => Cvest::$action, "type" => Cvest::$type ));   
    }
    
    
    /**
     * уведомление
    */
    function getNottification(){
        include(CORE_PATH."nottification/counter.php");
        include(CORE_PATH."nottification/message.php");
        return $this->answer(array( 'text' => $text, 'count' => $count, 'all' => $all, 'stop' => $stop ));
    }
    
    /**
     * рассылка заново
    */
    function restartNottification($data){
        $text = DBConnect::checkData($data[0]);
        #include("pznahar/nottification/counter.php");
        #include("pznahar/nottification/message.php");
        
        $file = fopen(CORE_PATH."nottification/counter.php", "w");
        $t = "<?php "."$"."count = 0; " ;        
        $t .= " $"."all = false; ";
        $t .= " $"."stop = false; ";
        $t .= "?>" ;
        
        fwrite($file,  $t );
        fclose($file);
        
        $file = fopen(CORE_PATH."nottification/message.php", "w");
        $t = "<?php "."$"."text = '".$text."'; " ;
        fwrite($file,  $t );
        fclose($file);
        
        return $this->answer(true);
    }
    
    /**
     * Изменить текст
    */
    function changeNottification($data){
        $text = DBConnect::checkData($data[0]);        
        #include("pznahar/nottification/counter.php");
        #include("pznahar/nottification/message.php");
        
        $file = fopen(CORE_PATH."nottification/message.php", "w");
        $t = "<?php "."$"."text = '".$text."'; " ;
        fwrite($file,  $t );
        fclose($file);
        
        return $this->answer(true);
    }
    
    /**
     * Остановить рассылку
    */
    function stopNottification(){        
        
        include(CORE_PATH."nottification/counter.php");
        include(CORE_PATH."nottification/message.php");
        
        $file = fopen(CORE_PATH."nottification/counter.php", "w");
        $t = "<?php "."$"."count = ".$count."; " ;        
        $t .= " $"."all = ".(($all)? 'true' : 'false')."; ";
        $t .= " $"."stop = true ;";
        $t .= "?>" ;
        
        fwrite($file,  $t );
        fclose($file);
        
        
        return $this->answer(true);
    }
    
    /**
     * Запустить рассылку
    */
    function startNottification(){        
        
        include(CORE_PATH."nottification/counter.php");
        include(CORE_PATH."nottification/message.php");
        
        $file = fopen(CORE_PATH."nottification/counter.php", "w");
        $t = "<?php "."$"."count = ".$count."; " ;        
        $t .= " $"."all = ".(($all)? 'true' : 'false')."; ";
        $t .= " $"."stop = false ;";
        $t .= "?>" ;
        
        fwrite($file,  $t );
        fclose($file);
        
        
        return $this->answer(true);
    }
    
    /**
     * Время средней сессии в игре
    */
    function getTimeGame(){
        $stat = new Statistic();
        return $this->answer($stat->getTimeGame());
    }
    /**
     * График активности (количество заходов) усредненного игрoка
     * [1,2,3,4]
    */
    function countGame($time){
        if( !is_array($time) || count($time) == 0 ){
            $time = array(1, 10, 30, 60);
        }
        $stat = new Statistic();
        return $this->answer($stat->countGame($time));
    }
     /**
     * время средней сессии
     * [1,2,3,4]
    */
    function timeGame($time = array()){
        if( !is_array($time) || count($time) == 0 ){
            $time = array(10, 10, 30, 60);
        }
        $stat = new Statistic();
        return $this->answer($stat->timeGame($time));
    }
    /**
     * Характеристики игроков - пол, возраст
     * [10, 20, 30, 40]
    */
    function propGamers($array = array()){
        if( !is_array($array) || count($array) == 0 ){
            $array = array(10, 20, 30, 40);
        }
        $stat = new Statistic();
        return $this->answer($stat->propGamers($array));
    }
    /**
     * Статистика покупки товаров
     * ["potion", 10]
    */
    function statGoods($data = array()){
        if(!$data){
            $data[] = "potion";
            $data[] = false;
        }
        $stat = new Statistic();
        return $this->answer($stat->statGoods($data[0], $data[1]));
    }
    
    /**
     * []
     * getChance
    */
    function getChance(){
        $this->logStart("getChance ");
        $arr = array('1'=>10, '2'=>20, '3'=>30, '4'=>15);
        $chance = new Chance();
        $this->logEnd();
        return $chance->get($arr);           
    }
    
    private function answer($data){        
        
        if($data === false){            
            return $this->error(Connect::$__error);
        }else{
            
            $s = new Session();
            $s->deleteAllSession();        
            
            return $this->complete($data);
        } 
    }

}
?>
